jQuery(function () {

	// TEMPLATES //

	var categoryTemplate = jQuery("<div><li><a href=\"{{url}}\">{{text}}</a></li></div>").html();
	// Damn stupid workarounds...
	var codeTemplateOpen = jQuery("<div><pre class=\"brush: {{brush}};\"></pre></div>").html().replace("</pre>", "");
	var codeTemplateClose = jQuery("<div><pre></pre></div>").html().replace("<pre>", "");

	// REQUEST HANDLERS //
	
	function onCategoriesReceived(data) {
		console.log("WORK ?");
		if (data.error == null) {
			addCategories(data.data);
		}
	};

	function onPostReceived(data) {
		console.log(JSON.stringify(data));
		if (data.error == null) {
			addTitle(data.data.title);
			addContent(data.data.content);
		}
	};

	// BLOG HANDLERS //

	function addCategories(categories) {
		var html = "";

		for (var i = 0; i < categories.length; i++) {
			html += categoryTemplate.replace("{{url}}", "#").replace("{{text}}", categories[i].value);
		}
		jQuery(html).appendTo("#categories ul");
	};

	function addContent(content) {
		removePost();
		addPost(content);
		importSnippetLibs(imports);
	}

	function addPost(post) {
		post = createSnippet(post);
		var paragrafs = post.split("\n\n");

		for (var i = 0; i < paragrafs.length; i++) {
			console.log("Paragraf: " + paragrafs[i]);
			jQuery("<p>" + paragrafs[i] + "</p>").appendTo("#mainContent article div");
		}
	};

	function addTitle(title) {
		jQuery("#blogTitle").text(title);
	};

	function removePost() {
		jQuery("#mainContent article div p").remove();
	};

	function createSnippet(content) {
		console.log("CREATE");
		var snippets = content.match(snippetPatternOpen);
		var tmp;

		for (var i = 0; i < snippets.length; i++) {
			tmp = snippets[i].substring(2, snippets[i].length - 2);
			if (dictionary[tmp] == null) {
				dictionary[tmp] = imports.length;
				imports.push(tmp);
			}
		}

		for (var i = 0; i < imports.length; i++) {
			content = content.replace(createSnipperPattern(imports[i]), 
				codeTemplateOpen.replace("{{brush}}", imports[i]));
		}

		return content.replace(snippetPatternClose, codeTemplateClose);
	};

	// UTIL METHODS //
	
	function getURLParameter(name) {
		var result = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(window.location.href);
		return (result != null && result.length > 0 ? result[1] : null);
	};

	function createSnipperPattern(pattern) {
		return new RegExp("(\\[\\[)(" + pattern + ")(\\]\\])", "g");
	};

	function importSnippetLibs(libs) {
		var counter = libs.length;

		for (var i = 0; i < libs.length; i++) {
			jQuery.getScript(baseURL + "/libs/shBrush" + libs[i] + ".js", function(data, textStatus, jqxhr) {
				if (--counter == 0) {
					SyntaxHighlighter.highlight();
				}
			});
		}
	};

	// MAIN //
	
	var baseURL = "http://springleafweb.appspot.com";
	var categotyURL = baseURL + "/get-all-categories";
	var postURL = baseURL + "/get-blog-post";
	var post = getURLParameter("post");

	var dictionary = new Object();
	var imports = new Array();

	var snippetPatternOpen = /(\[\[)([A-Za-z0-9]*?)(\]\])/g;
	var snippetPatternClose = /(\[\[\/)([A-Za-z0-9]*?)(\]\])/g;
	
	jQuery.get(categotyURL, onCategoriesReceived);
	jQuery.get((post != null ? postURL + "?post=" + post : postURL), onPostReceived);

	// EXPERIMENTS //

	//var html = "Here comes some code... [[AS3]]public function doSOmething():void {}[[/AS3]] more code...";
	//addContent(html);
});